package cn.xw.DirectExchange;

import cn.xw.utils.ChannelUtil;
import com.rabbitmq.client.Channel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-12 0:09
 * ErrConsumer(错误队列)
 */
public class ErrConsumer {

    //通过日志管理器获取Logger对象
    static Logger logger = LogManager.getLogger(Producer.class);
    //交换机名称
    public static final String LOG_EXCHANGE = "LogExchange";
    //队列名称
    public static final String ERR_QUEUE = "ErrQueue";
    //路由绑定关系 Routing Key
    public static final String ERR_KEY = "ErrKey";

    public static void main(String[] args) throws IOException {
        //调用自己的工具类获取信道
        Channel channel = ChannelUtil.getChannel();

        //声明exchange交换机 并设置为直接交换机；防止消费者先启动报错，找不到交换机
        //channel.exchangeDeclare(LOG_EXCHANGE, BuiltinExchangeType.DIRECT,
        //        true, false, false, null);

        //创建一个基本日志队列
        channel.queueDeclare(ERR_QUEUE, true, false, false, null);
        //队列绑定到交换机上，并通过路由key来对应两者的连接
        channel.queueBind(ERR_QUEUE, LOG_EXCHANGE, ERR_KEY);
        logger.info("ErrConsumer(错误队列)开始监听队列消息....");
        //接收队列消息
        channel.basicConsume(ERR_QUEUE, true, (consumerTag, message) -> {
            logger.info("ErrConsumer(错误队列)获取队列信息并处理：{}", new String(message.getBody(), StandardCharsets.UTF_8));
        }, consumerTag -> {
            logger.info("监听的队列(ErrConsumer)出现异常；可能队列被删除！{}", consumerTag);
        });
    }
}
